import React, {PropsWithChildren, ReactNode, useMemo, useState} from 'react'
import {Text, View} from "@tarojs/components";
import {Button, Cell, InputNumber, Picker, Input, ConfigProvider} from "@nutui/nutui-react-taro";
import {NumberIdAndName} from "../types/BasicModels";
import {QueryGoodsUnitResponse, SubGoodsResponse} from "../apis/GoodsApi";
import {ArrowDown, ArrowUp, Edit} from "@nutui/icons-react-taro";
import styles from "./OrderListItem.module.sass";
import Taro from '@tarojs/taro';
import Prompt from "../components/Prompt"

export interface OrderListItemProps extends PropsWithChildren {
    data: OrderListItemData
    canEdit?: boolean
    onUpdateAmount?: (amount: number, unitId?: number) => Promise<void>
    onDelete?: () => Promise<void>
    onClick?: () => void
    onUpdateNote?: (note: string) => Promise<void>
    onUpdatePrice?: (price:number)=>Promise<void>
    customDescriptionColumn?: (numberNode:ReactNode, amountNode:ReactNode, noteNode:ReactNode,priceNode:ReactNode)=> ReactNode
    id?:string
}

export interface OrderListItemData {
    id: number
    name: string
    amountInOrder: number
    barcode: string
    unit?: NumberIdAndName
    units: QueryGoodsUnitResponse[]
    subGoods?: SubGoodsResponse
    note?: string
    price?:number
}

const OrderListItem: React.FC<OrderListItemProps> = (props) => {
    let data = props.data;
    const [loading, setLoading] = useState(false)
    const [showUnitPicker, setShowUnitPicker] = useState(false)
    const basicUnit = useMemo(() => {
        return data.units.find(it => it.basicMultiple === 0)
    }, [data]);

    const [updateAmountTimer, setUpdateAmountTimer] = useState<number>()

    async function doUpdateAmount(amount: number, unitId?: number) {
        if (!loading && !!props.onUpdateAmount) {
            if (!!updateAmountTimer) {
                clearTimeout(updateAmountTimer)
            }

            let timeout = setTimeout(async () => {
                setLoading(true)
                try {
                    await props.onUpdateAmount!(amount, unitId)
                    setUpdateAmountTimer(undefined)
                } finally {
                    setLoading(false)
                }
            }, 300) as unknown as number;
            setUpdateAmountTimer(timeout)
        }
    }

    const [amountInOrder, setAmountInOrder] = useState(data.amountInOrder)
    const currentUnit = useMemo(() => {
        return data.units?.find(it => it.id === data.unit?.id) ?? basicUnit
    }, [data]);
    let name = useMemo(() => {
        return data.subGoods ? data.subGoods.name + `（${data.name}）` : data.name
    }, [data])
    let number = useMemo(() => {
        return data.subGoods ? data.barcode + "|" + data.subGoods.number : data.barcode
    }, [data])

    const [notePromptVisible,setNotePromptVisible] = useState(false)
    const [pricePromptVisible,setPricePromptVisible] = useState(false)
    return <>
        <Cell id={props.id} title={<Text className={styles.title}>{name}</Text>}
            onClick={props.onClick}
            // @ts-ignore
              onLongPress={async () => {
                  let result = (await Taro.showModal({
                      title: `确定要删除“${name}“吗`,
                  }))
                  if (result.confirm)
                      await (props.onDelete && props.onDelete())
              }}
              description={<>
                  <View style={{display: "flex", flexDirection: "column",}}>


                      {
                          (()=>{
                             const noteNode = props.canEdit?<View style={{display: "flex", flexDirection: "row", alignItems: "center"}}
                                                                  onClick={props.canEdit ? async (event) => {
                                                                      event.stopPropagation()
                                                                      setNotePromptVisible(true)
                                                                  } : undefined}>
                                 { <Edit/>}
                                 {<Input value={data.note} type={"text"} readOnly placeholder={"备注"}/>}
                                 { notePromptVisible&&<Prompt initialValue={data.note} onConfirm={async value => {
                                     if (props.onUpdateNote) {
                                         try {
                                             await props.onUpdateNote(value)
                                         } catch (e) {

                                         }
                                     }
                                 }} visible={notePromptVisible} onCancel={() => setNotePromptVisible(false)}
                                                             title={`请输入备注`}/>}
                             </View>:<Text>{data.note}</Text>;
                              const amountNode = props.canEdit ? <View style={{display: "flex", flexDirection: "row", alignItems: "center"}}>
                                      <ConfigProvider theme={{
                                          nutuiInputnumberButtonWidth: '24px',
                                          nutuiInputnumberButtonHeight: '24px',
                                          nutuiInputnumberButtonBackgroundColor: `#f4f4f4`,
                                          nutuiInputnumberInputBackgroundColor: '#fff',
                                          nutuiInputnumberInputMargin: '0 2px',
                                      }}>
                                          <InputNumber value={amountInOrder}
                                                       async
                                                       readOnly={loading}
                                                       onChange={async value => {
                                                           let amount = Number(value);
                                                           await doUpdateAmount(amount, data.unit?.id)
                                                           setAmountInOrder(amount)
                                                       }}
                                                       onClick={(event)=>{
                                                           event.stopPropagation()
                                                       }}
                                          />
                                      </ConfigProvider>
                                      {!!data.units.length &&
                                          <Button size={"mini"} style={{marginLeft: 24}} fill={"none"} onClick={(e) => {
                                              e.stopPropagation()
                                              setShowUnitPicker(true)
                                          }} rightIcon={showUnitPicker ? <ArrowUp/> :
                                              <ArrowDown/>}><Text>{currentUnit?.name}{currentUnit && basicUnit && basicUnit?.id !== currentUnit?.id ? `=${(data.amountInOrder??0)*currentUnit.basicMultiple}${basicUnit.name}` : ""}</Text></Button>}
                                  </View> : <Text>{data.amountInOrder}{data.unit?.name}</Text>;
                              const numberNode = <Text>{number}</Text>
                              const priceNode = props.onUpdatePrice ? (props.canEdit?<View style={{display:"flex",flexDirection:"row",alignItems:"center"}} onClick={(event)=> {
                                  event.stopPropagation()
                                  setPricePromptVisible(true)
                              }}>
                                  {<Input value={data.price?.toString()} type={"digit"} readOnly placeholder={"退货价"} style={{width:100}}/>}
                                  <Text>元</Text>
                                  {pricePromptVisible&&<Prompt initialValue={data.price?.toString()??"0"} onConfirm={async value => {
                                      if (props.onUpdatePrice) {
                                          try {
                                              await props.onUpdatePrice(Number(value)||0)
                                          } catch (e) {

                                          }
                                      }
                                  }} visible={pricePromptVisible} onCancel={() => setPricePromptVisible(false)}
                                                              title={`请输入退货价`}/>}
                              </View>:<Text>单价{data.price}元，小计{(data.price??0)*data.amountInOrder}</Text>):<></>
                              return props.customDescriptionColumn?props.customDescriptionColumn(numberNode,amountNode,noteNode,priceNode):[
                                  numberNode,
                                  <View style={{display:"flex",flexDirection:"row",justifyContent:"space-between"}}>
                                      {amountNode}
                                      {priceNode}
                                  </View>,
                                  noteNode,
                              ]
                          })()
                      }

                  </View>
              </>}/>
        <Picker title={"请选择单位"} visible={showUnitPicker}
                options={[
                    data.units.map(unit => {
                        let text = unit.name;
                        if (unit.basicMultiple !== 0 && !!basicUnit) {
                            text += `=${unit.basicMultiple}${basicUnit.name}`
                        }
                        return {
                            value: unit.id,
                            text,
                        }
                    })
                ]}
                onClose={() => setShowUnitPicker(false)}
                onConfirm={async (_, selectedValue) => {
                    await doUpdateAmount(data.amountInOrder, Number(selectedValue[0]))
                }}/>
    </>
}

export default OrderListItem


